<?php
//header("Content-type:text/html;charset=utf-8");
error_reporting(E_ALL);
set_time_limit(60);

ob_implicit_flush(1);
//echo "<meta charset='GBK'>";
$address = '192.168.0.101';
$port=10862;
//创建端口
function gu($str){
    return iconv("GBK","UTF-8",$str);
}
if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    die( "socket_create() failed :reason:" . gu(socket_strerror(socket_last_error($sock))) . "<br>");
}

//绑定
if (socket_bind($sock, $address, $port) === false) {
    die( "socket_bind() failed :reason:" . gu(socket_strerror(socket_last_error($sock))) . "<br>");
}
echo $address.$port."<br>";ob_flush();
//监听
if (socket_listen($sock, 5) === false) {
    die( "socket_bind() failed :reason:" . gu(socket_strerror(socket_last_error($sock))) . "<br>");
}
echo 3;ob_flush();
do {
    //得到一个链接
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accepty() failed :reason:".gu(socket_strerror(socket_last_error($sock))) . "<br>";
        break;
    }
    ob_flush();
    //welcome  发送到客户端
    $msg = "<font color='red'>server send:welcome</font><br/>";
    socket_write($msgsock, $msg, strlen($msg));
    echo 'read client message<br>';ob_flush();
    $buf = socket_read($msgsock, 8192);
    $talkback = "received message:$buf<br>";
    echo $talkback;ob_flush();
    if (false === socket_write($msgsock, $talkback, strlen($talkback))) {
        echo "socket_write() failed reason:" . gu(socket_strerror(socket_last_error($sock))) ."<br>";ob_flush();
    } else {
        echo 'send success';ob_flush();
    }
    socket_close($msgsock);
} while(true);
//关闭socket
socket_close($sock);


?>